import http from './interface'
import qs from 'qs'
// let baseUrl = 'https://wkbar.case.nbyuyuan.com'
let baseUrl = "https://wkbar.nbxinyitec.com"
// let baseUrl = 'http://backend_wkbar_bak.localhost'
import * as storage from '@/common/storage'

const BASE_URL = process.env.NODE_ENV === 'production' ? baseUrl : ''
let storeConf = {}

export const post = (url, data = {}, extend = {
  isQuery: false,
  isJson: true
}) => {
  let defaultConfig = {}
	storeConf = storage.get('storeConf', false)
	storeConf = storeConf ? JSON.parse(storeConf) : storeConf
  if (storeConf.table_id) {
    data.table_id = storeConf.table_id
  }
  if (storeConf.device_num) {
    data.device_num = storeConf.device_num
  }
  if (extend.isQuery) {
    defaultConfig = {
      url: url + jsonToQueryString(data),
      method: 'POST',
      headers: {},
      baseUrl: BASE_URL
    }
  } else {
    defaultConfig = {
      url: url,
      method: 'POST',
      data: extend.isJson ? data : qs.stringify(data), // 通过isJson来确定传参格式是json还是formData
      headers: {},
      baseUrl: BASE_URL
    }
  }
  return http.request(defaultConfig)
}

const jsonToQueryString = (json) => {
  return (
    '?' +
    Object.keys(json)
    .map((key) => {
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
    .join('&')
  )
}

export const get = (url, data = {}, extend = {}) => {
  let defaultConfig = {}
	storeConf = storage.get('storeConf', false)
	storeConf = storeConf ? JSON.parse(storeConf) : storeConf
  if (storeConf.table_id) {
    data.table_id = storeConf.table_id
  }
  if (storeConf.device_num) {
    data.device_num = storeConf.device_num
  }
  defaultConfig = {
    url: url,
    method: 'GET',
    data: data,
    headers: {},
    baseUrl: BASE_URL
  }
  return http.request(defaultConfig)
}

// 默认全部导出  import api from '@/common/vmeitime-http/'
export default {
  post,
  get
}
